package com.share.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.share.domain.Lexicon;
import com.share.domain.Result;
import com.share.domain.SysUser;

import com.share.service.LexiconService;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @program: share-admin
 * 描述：
 * @author: XLX
 * @create: 2022-12-06 00:03
 **/
@RestController
@RequestMapping("/sys/lexicon")
public class LexiconController extends BaseController {

    @Autowired
    LexiconService lexiconService;

    @GetMapping("/info/{id}")
    public Result info(@PathVariable(name = "id") Long id){
        Lexicon lexicon = lexiconService.getInfoById(id);

        return Result.succ(lexicon);
    }


    @GetMapping("/list")
    public Result list(String name){

        Page<Lexicon> page = lexiconService.findPage(name,getPage());

        return Result.succ(page);
    }


    @GetMapping("/lexicons")
    public Result lexicons(){

        List<Lexicon> list = lexiconService.list();
        return Result.succ(list);
    }





    @PostMapping("/save")
    public Result save(@Validated @RequestBody Lexicon lexicon, Principal principal){
        if (principal!=null){   //如果当前用户存在
            SysUser sysUser = sysUserService.getByUsername(principal.getName());
            lexicon.setUid(sysUser.getId());  //设置创建人
        }

        lexicon.setCreated(new Date());
        lexiconService.save(lexicon);
        return Result.succ(lexicon);
    }


    @PostMapping("/update")
    public Result update(@Validated @RequestBody Lexicon lexicon){
        lexicon.setUpdated(new Date());
        lexiconService.updateById(lexicon);
        return Result.succ(lexicon);
    }


    @PostMapping("/delete")
    @Transactional
    public Result delete(@RequestBody Long[] ids){
        //删除词条
        lexiconService.removeByIds(Arrays.asList(ids));

        return Result.succ("词条删除成功");

    }

}